var text = [{
  title: '详情', endTime: '申请截止时间', reward: '奖励或回报', deadline: '任务截止期限',
  sign_up: '申请', ph: '发送申请时简单自我介绍一下...', like: '赞', comment: '评论', 
  cancel: '取消', send: '发送', sending: '正在发送', succ: '申请成功', mod: '修改',
  mod_succ: '修改成功',short: '介绍太短了，申请至少15字', fail: '您已申请',
  fail_tip: '再次申请将会覆盖原有记录，确定要重复申请吗？',
  msg_send: '申请已发送，正在等待任务发布者审核',
  msg_modify: '修改成功，正在等待任务发布者审核',
  msg_receive: '有同学申请了你发布的任务，赶紧去看看吧！',
}, {
  title: 'Details', endTime: 'Deadline for submissions', reward: 'Rewards', 
  deadline: 'Deadline for whole project',
  sign_up: '申请', ph: '发送申请时简单自我介绍一下...', like: '赞', comment: '评论', 
  cancel: '取消', send: '发送', sending: '正在发送', succ: '申请成功', mod: '修改',
  mod_succ: '修改成功',short: '介绍太短了，申请至少15字', fail: '您已申请',
  fail_tip: '再次申请将会覆盖原有记录，确定要重复申请吗？',
  msg_send: '申请已发送，正在等待任务发布者审核',
  msg_modify: '修改成功，正在等待任务发布者审核',
  msg_receive: '有同学申请了你发布的任务，赶紧去看看吧！',
}],
tip_register = [
  { tip: '登录后才能操作噢~', confirm: '前往登录', cancel: '先看看' },
  { tip: '登录后才能操作噢~', confirm: '前往登录', cancel: '先看看' },
];

var animating, sending;
var formid1, formid2;
Page({

  data: {
    isMine: false,  // 判断是否是用户自己的项目
    showMask: true,
    sign: false,
  },

  onLoad: function (options) {
    sending = animating = 0;
    let item = JSON.parse(options.content)
    if (item.gmtdead != '0') 
      item.deadline = wx.formatTime(new Date(parseInt(item.gmtdead) * 1e3), '/');
    if (item.iduser == wx.appData.user.iduser)
      this.setData({ isMine: true })
    this.setData({ 
      item: item, 
      text: text[wx.lang],
      theme: wx.theme,
    });
    console.log(item)
    // wx.createSelectorQuery().select('.background').boundingClientRect(bg => {
    //   this.setData({ contentHight: bg.height / 8 })
    //   console.log(this.data.contentHight)
    // }).exec();
  },

  onShow() {
    wx.onShow(this, text[wx.lang].title, wx.theme);
    let query1 = wx.createSelectorQuery(),
    query2 = wx.createSelectorQuery();
    query1.select('.content').boundingClientRect(content => {
      query2.select('.title').boundingClientRect(title => {
        let scale = parseFloat(wx.system.width / 750);
        this.setData({ ch: content.height - 2 * title.height - 40 * scale });
        console.log(this.data.ch)
      }).exec(); 
    }).exec();
  },

  sign(form1) {
    formid1 = form1.detail.formId || '';
    if (animating++) return;
    if (!wx.appData.user.name) {
      wx.modal(null, tip_register[wx.lang].tip,
        tip_register[wx.lang].cancel, tip_register[wx.lang].confirm,
        null, null,  // navigate to registration if not registered.
        () => { wx.nav('../register/register')}
      );
      return animating--;
    }
    wx.slide_v(this, ['group1'], wx.system.height, 0, .5, () => { 
      this.setData({ hideGroup: true });
      wx._slide_v(this, ['group2'], wx.system.height, 0, () => {
        wx.slide_v(this, ['group2'], 0, 1, 0, () => {
          animating = 0;
        })
      })
    })
    wx.hide(this, ['content1'], () => {
      this.setData({ sign: true });
      wx.show(this, ['content2']);
    })
  }, 
  
  input(e) { 
    this.setData({ inputText: e.detail.value });
  },
  modify() {
    let content = encodeURIComponent(JSON.stringify(this.data.item));
    let url = `/pages/module/index/release/detail/detail`
    wx.onHide(this, `${url}?content=${content}&gotoModify`);
    
  },
  cancel() { wx.toast('正在开发') },

  back() {
    if (animating++) return;
    wx.slide_v(this, ['group2'], wx.system.height, 0, .5, () => {
      this.setData({ hideGroup: false });
      wx._slide_v(this, ['group1'], wx.system.height, 0, () => {
        wx.slide_v(this, ['group1'], 0, 1, 0, () => {
          animating = 0;
        });
      });
    });
    wx.hide(this, ['content2'], () => {
      this.setData({ sign: false, });
      wx.show(this, ['content1']);
    });
  },

  send(form2) {
    formid2 = form2.detail.formId || '';
    if (sending++) return;
    if (!!this.data.inputText &&this.data.inputText[10]) {
      let data = {   // 用以存入数据库
        description: this.data.inputText,
        idPractice: this.data.item.idpractice,
        idUser: wx.appData.user.iduser,
      },
      getFormId = {   // 用以获取 openid
        formid: formid2,
        idPractice: this.data.item.idpractice,
      },
      sendMsg = {     // 用以获取发布模板消息
        touser: wx.appData.user.openid,
        formId: formid1,
        page: '/pages/home/preload/preload?action=signup',
        data: {
          keyword1: { value: wx.appData.user.name },
          keyword2: { value: wx.appData.user.phone },
          keyword3: { value: this.data.item.title },
          keyword4: { value: text[0].msg_send }
        },
        templateId: 'oz2ULM4EP11EoiPPcgmDCos0X1jLSuzzs3xIZcpMMm0',
      };
      wx.post('PracticeItem.joinPractice', data, res => {
        // 从返回的数据中获取 idpracticeitem
        getFormId.idPracticeItem = res.data;   
        if (res.success) {
          wx.toast(text[wx.lang].succ, 1);
          wx.appData.user.signup = parseInt(wx.appData.user.signup) + 1;
          // wx.post('Practice.sendTemplateMessage', getFormId, publisher => {
          //   if (publisher) {
          //     wx.toast('申请失败2\nSign up failed')
          //     return;
          //   }
          //   wx.call('templateMsg', sendMsg);
          //   // 向发布者发送模板消息
          //   sendMsg.touser = publisher.data.openid,
          //   sendMsg.formId = publisher.data.formid;
          //   sendMsg.data.keyword4.value = text[0].msg_receive;
          //   page: '/pages/home/preload/preload?action=publish',
          //   wx.call('templateMsg', sendMsg);
          // })
          setTimeout(() => {
            wx.onHide(this, 1, null, null, () => {
              sending = 0;
            });
          }, 1000);
        } else if (res.errCode == 102) {   // having signed up
          wx.modal(text[wx.lang].fail, text[wx.lang].fail_tip,
          text[wx.lang].cancel, null, null, null, () => {
            let data = {
              practiceItemInfo: { description: this.data.inputText },
              idPracticeItem: res.data.idpracticeitem,
            };
            wx.post('PracticeItem.updatePracticeItem', data, () => {
              wx.toast(text[wx.lang].mod_succ, 1);
              // send template message
              getFormId.idPracticeItem = res.data.idpracticeitem;
              sendMsg.data.keyword4.value = text[0].msg_modify;
              // wx.post('Practice.sendTemplateMessage', getFormId, publisher => {
              //   wx.call('templateMsg', sendMsg)
              // })

              setTimeout(() => {
                wx.onHide(this, 1, null, null, () => {
                  sending = 0;
                });
              }, 1000);
            }, text[wx.lang].sending);
          })
        } else {
          wx.toast('申请失败\nSign up failed')
        }
      }, text[wx.lang].sending)
    } else {
      wx.toast(text[wx.lang].short, 0, 1);
      sending = 0;
    }
  }, 

  onShareAppMessage: function () {
    return wx.onShareAppMessage();
  }
})